<script setup>
import { ref, onMounted, reactive, toRefs } from 'vue'
import {
  getMerchantListAPI,
  addMerchantAPI,
  updateMerchantAPI,
  deleteMerchantAPI,
  getMerchantDetailAPI
} from '@/api/merchant'
import { uploadFileAPI } from '@/api/upload'

// 搜索和筛选条件
const searchForm = reactive({
  merchantName: '',
  location: ''
})

// 分页相关
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 弹窗/抽屉相关
const dialogVisible = ref({
  add: false,
  edit: false,
  detail: false
})
const detailLoading = ref(false)

// 表单数据
const formData = reactive({
  id: '',
  merchantName: '',
  location: '',
  businessMealsType: [],
  image: ''
})

// 商家详情数据
const merchantDetail = reactive({
  id: 0,
  merchantName: '',
  status: 0,
  location: '',
  businessMealsType: [],
  merchantRating: 0.0,
  ratingCount: 0,
  image: '',
  createTime: '',
  updateTime: '',
  createUser: 0,
  dishList: []
})

// 营业类型选项
const businessTypes = [
  { label: '早餐', value: 1 },
  { label: '午餐', value: 2 },
  { label: '晚餐', value: 3 },
  { label: '零食', value: 4 }
]

// 获取商家列表
const getMerchantList = async () => {
  if (loading.value) return

  try {
    loading.value = true
    const res = await getMerchantListAPI(
      pagination.currentPage,
      pagination.pageSize,
      searchForm.merchantName || undefined,
      searchForm.location || undefined
    )

    // 检查接口返回状态
    if (res.data.code === 1 && res.data.data) {
      tableData.value = res.data.data.records || []
      pagination.total = res.data.data.total || 0
    } else {
      ElMessage.warning('获取商家列表失败')
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    ElMessage.error('获取商家列表失败')
    console.error('获取商家列表错误:', error)
  } finally {
    loading.value = false
  }
}

// 搜索和筛选
const handleSearch = () => {
  pagination.currentPage = 1
  getMerchantList()
}

// 重置筛选条件
const handleReset = () => {
  searchForm.merchantName = ''
  searchForm.location = ''
  pagination.currentPage = 1
  getMerchantList()
}

// 分页处理
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  getMerchantList()
}

// 打开添加弹窗
const handleAdd = () => {
  // 重置表单
  Object.keys(formData).forEach((key) => {
    formData[key] = ''
  })
  dialogVisible.value.add = true
}

// 打开编辑弹窗
const handleEdit = (row) => {
  //处理商家营业类型
  if (row.businessMealsType) {
    row.businessMealsType = row.businessMealsType
      .toString()
      .split('')
      .map((id) => parseInt(id))
  } else {
    row.businessMealsType = []
  }

  // 填充表单数据
  Object.assign(formData, row)
  dialogVisible.value.edit = true
}

// 查看商家详情
const handleView = async (id) => {
  try {
    detailLoading.value = true
    const res = await getMerchantDetailAPI(id)

    // 检查接口返回状态（根据文档，code为1时成功）
    if (res.data.code === 1 && res.data.data) {
      Object.assign(merchantDetail, res.data.data)
      dialogVisible.value.detail = true
    } else {
      ElMessage.warning('获取商家详情失败')
    }
  } catch (error) {
    ElMessage.error('获取商家详情失败')
    console.error('获取商家详情错误:', error)
  } finally {
    detailLoading.value = false
  }
}

// 提交表单（添加或编辑）
const handleSubmit = async (isEdit = false) => {
  if (!formData.merchantName) {
    ElMessage.warning('请输入商家名称')
    return
  }

  //处理营业类型ID
  const submitData = {
    ...formData,
    businessMealsType: formData.businessMealsType.sort((a, b) => a - b).join('')
  }

  try {
    if (isEdit) {
      // 编辑商家

      await updateMerchantAPI(submitData)
      ElMessage.success('商家更新成功')
      dialogVisible.value.edit = false
    } else {
      // 添加商家
      await addMerchantAPI(submitData)
      ElMessage.success('商家添加成功')
      dialogVisible.value.add = false
    }
    getMerchantList() // 重新获取列表
  } catch (error) {
    ElMessage.error(isEdit ? '更新商家失败' : '添加商家失败')
    console.error(error)
  }
}

// 删除商家
const handleDelete = async (id, name) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除商家 "${name}" 吗？此操作不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteMerchantAPI(id)
    ElMessage.success('删除成功')
    getMerchantList() // 重新获取列表
  } catch (error) {
    // 用户取消删除或操作失败
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

// 图片上传处理
const handleUpload = async (uploadFile) => {
  try {
    // 创建FormData对象并添加文件
    const uploadFormData = new FormData()
    uploadFormData.append('file', uploadFile.file)

    // 调用上传接口
    const response = await uploadFileAPI(uploadFormData)

    // 从响应中获取图片地址并设置
    if (response.data && response.data.data) {
      formData.image = response.data.data
      ElMessage.success('图片上传成功')
      return true // 上传成功
    } else {
      ElMessage.error('上传失败，未返回图片地址')
      return false
    }
  } catch (error) {
    ElMessage.error('图片上传失败')
    console.error('上传错误:', error)
    return false
  }
}

// 格式化营业类型
const formatBusinessType = (type) => {
  if (!type) return ''

  const ids = type
    .toString()
    .split('')
    .map((id) => parseInt(id))
  return ids
    .map((id) => {
      const typeItem = businessTypes.find((t) => t.value === id)
      return typeItem ? typeItem.label : ''
    })
    .filter((label) => label)
    .join('、')
}

// 初始加载
onMounted(() => {
  getMerchantList()
})

// 解构响应式对象
const { currentPage, pageSize, total } = toRefs(pagination)
</script>

<template>
  <div class="shop-management">
    <div class="page-header">
      <h1>商家管理</h1>
      <div class="header-actions">
        <el-input
          v-model="searchForm.merchantName"
          placeholder="搜索商家名称"
          style="width: 200px; margin-right: 12px"
          clearable
        />
        <el-input
          v-model="searchForm.location"
          placeholder="搜索位置"
          style="width: 200px; margin-right: 12px"
          clearable
        />
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset" style="margin-left: 12px"
          >重置</el-button
        >
        <el-button type="primary" @click="handleAdd" style="margin-left: 12px">
          添加商家
        </el-button>
      </div>
    </div>

    <el-table
      :data="tableData"
      style="width: 100%"
      v-loading="loading"
      element-loading-text="加载中..."
      empty-text="暂无商家数据"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column label="商家图片" width="100">
        <template #default="scope">
          <el-image
            :src="scope.row.image"
            style="width: 60px; height: 60px"
            fit="cover"
            :alt="scope.row.merchantName"
          />
        </template>
      </el-table-column>
      <el-table-column prop="merchantName" label="商家名称" min-width="150" />
      <el-table-column prop="location" label="地址" min-width="200" />
      <el-table-column label="营业类型" width="120">
        <template #default="scope">
          {{ formatBusinessType(scope.row.businessMealsType) }}
        </template>
      </el-table-column>
      <el-table-column label="评分" width="100">
        <template #default="scope">
          {{ scope.row.merchantRating.toFixed(1) }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160" />
      <el-table-column label="操作" width="240">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="handleView(row.id)">
            查看
          </el-button>
          <el-button size="small" type="warning" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(row.id, row.merchantName)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        background
        layout="total, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加商家弹窗 -->
    <el-dialog title="添加商家" v-model="dialogVisible.add" :width="600">
      <el-form :model="formData" label-width="120px">
        <el-form-item label="商家名称" required>
          <el-input
            v-model="formData.merchantName"
            placeholder="请输入商家名称"
          />
        </el-form-item>
        <el-form-item label="商家位置">
          <el-input v-model="formData.location" placeholder="请输入商家位置" />
        </el-form-item>
        <el-form-item label="营业类型">
          <el-select
            v-model="formData.businessMealsType"
            placeholder="请选择营业类型"
            multiple
          >
            <el-option
              v-for="type in businessTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商家图片">
          <el-upload
            :http-request="handleUpload"
            list-type="picture"
            :headers="{ 'Content-Type': undefined }"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
          <el-image
            v-if="formData.image"
            :src="formData.image"
            style="width: 100px; height: 100px; margin-top: 10px"
            fit="cover"
            :alt="formData.merchantName"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible.add = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit(false)">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑商家弹窗 -->
    <el-dialog title="编辑商家" v-model="dialogVisible.edit" :width="600">
      <el-form :model="formData" label-width="120px">
        <el-form-item label="ID">
          <el-input v-model="formData.id" disabled />
        </el-form-item>
        <el-form-item label="商家名称" required>
          <el-input
            v-model="formData.merchantName"
            placeholder="请输入商家名称"
          />
        </el-form-item>
        <el-form-item label="商家位置">
          <el-input v-model="formData.location" placeholder="请输入商家位置" />
        </el-form-item>
        <el-form-item label="营业类型">
          <el-select
            v-model="formData.businessMealsType"
            placeholder="请选择营业类型"
            multiple
          >
            <el-option
              v-for="type in businessTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商家图片">
          <el-upload
            :http-request="handleUpload"
            list-type="picture"
            :headers="{ 'Content-Type': undefined }"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
          <el-image
            v-if="formData.image"
            :src="formData.image"
            style="width: 100px; height: 100px; margin-top: 10px"
            fit="cover"
            :alt="formData.merchantName"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible.edit = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit(true)">确定</el-button>
      </template>
    </el-dialog>

    <!-- 商家详情弹窗 -->
    <el-dialog
      title="商家详情"
      v-model="dialogVisible.detail"
      :width="800"
      :close-on-click-modal="false"
    >
      <div v-loading="detailLoading" element-loading-text="加载中...">
        <!-- 商家基本信息 -->
        <div class="merchant-basic-info">
          <el-descriptions column="2" border>
            <el-descriptions-item label="ID">{{
              merchantDetail.id
            }}</el-descriptions-item>
            <el-descriptions-item label="商家名称">{{
              merchantDetail.merchantName
            }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="merchantDetail.status === 1 ? 'success' : 'info'">
                {{ merchantDetail.status === 1 ? '营业中' : '已关闭' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="营业类型">{{
              formatBusinessType(merchantDetail.businessMealsType)
            }}</el-descriptions-item>
            <el-descriptions-item label="地址">{{
              merchantDetail.location
            }}</el-descriptions-item>
            <el-descriptions-item label="评分"
              >{{ merchantDetail.merchantRating.toFixed(1) }} ({{
                merchantDetail.ratingCount
              }}条评价)</el-descriptions-item
            >
            <el-descriptions-item label="创建时间">{{
              merchantDetail.createTime
            }}</el-descriptions-item>
            <el-descriptions-item label="更新时间">{{
              merchantDetail.updateTime
            }}</el-descriptions-item>
          </el-descriptions>

          <!-- 商家图片 -->
          <div class="merchant-image" v-if="merchantDetail.image">
            <h4 style="margin: 16px 0 8px 0">商家图片</h4>
            <el-image
              :src="merchantDetail.image"
              style="max-width: 100%; max-height: 300px"
              fit="contain"
              :alt="merchantDetail.merchantName"
            />
          </div>
        </div>

        <!-- 商家菜品列表 -->
        <div class="merchant-dishes">
          <h3 style="margin: 20px 0 10px 0">
            商家菜品 ({{ merchantDetail.dishList.length }})
          </h3>

          <el-table
            :data="merchantDetail.dishList"
            empty-text="该商家暂无菜品"
            style="width: 100%"
          >
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column label="菜品图片" width="100">
              <template #default="scope">
                <el-image
                  :src="scope.row.image"
                  style="width: 50px; height: 50px"
                  fit="cover"
                  :alt="scope.row.dishName"
                />
              </template>
            </el-table-column>
            <el-table-column prop="dishName" label="菜品名称" />
            <el-table-column prop="price" label="价格" width="100">
              <template #default="scope"
                >¥{{ scope.row.price.toFixed(1) }}</template
              >
            </el-table-column>
            <el-table-column prop="calorie" label="热量" width="100" />
            <el-table-column prop="dishRating" label="评分" width="100">
              <template #default="scope">{{
                scope.row.dishRating.toFixed(1)
              }}</template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <el-button @click="dialogVisible.detail = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.shop-management {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    flex-wrap: wrap;
    gap: 12px;

    h1 {
      font-size: 1.5rem;
      color: #1a202c;
      margin: 0;
    }

    .header-actions {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 12px;
    }
  }

  .pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 24px;
  }

  .merchant-basic-info {
    margin-bottom: 10px;
  }

  .merchant-image {
    margin: 10px 0;
    padding: 10px;
    background-color: #f9f9f9;
    border-radius: 4px;
  }

  .merchant-dishes {
    margin-top: 10px;
  }
}
</style>
